package com.etime.yqtsponsor.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.etime.yqtsponsor.common.BaseMessage;
import com.etime.yqtsponsor.common.PageMessage;
import com.etime.yqtsponsor.common.PojoMessage;
import com.etime.yqtsponsor.dto.VoteRegisterDto;
import com.etime.yqtsponsor.dto.VoteRegisterDtos;
import com.etime.yqtsponsor.pojo.ActiveGroup;
import com.etime.yqtsponsor.pojo.ActiveTheme;
import com.etime.yqtsponsor.pojo.ActiveTimeLine;
import com.etime.yqtsponsor.pojo.VoteRegister;
import com.etime.yqtsponsor.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: LouisLew
 * @date: 2022/07/19/16:58
 * @description: 参与活动用户的控制层
 */
@Api(tags = "参与活动用户的数据接口")
@RestController
@RequestMapping("/active/register")
public class VoteRegisterController {

    @Autowired
    private VoteRegisterService voteRegisterService;
    @Autowired
    private ActiveThemeService activeThemeService;
    @Autowired
    private ActiveTimeLineService activeTimeLineService;
    @Autowired
    private UserBehaviorService userBehaviorService;
    @Autowired
    private ActiveGroupService activeGroupService;

    @ApiOperation("分页查询参与活动选手")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "第几页 默认第1页"),
            @ApiImplicitParam(name = "pageSize", value = "每页多少行 默认10行/页"),
            @ApiImplicitParam(name = "activeId",value = "活动Id 必传"),
            @ApiImplicitParam(name = "title", value = "搜索框-->作品名称和选手的微信名"),
    })
    @GetMapping("/page")
    public PageMessage<VoteRegisterDto> selectRegisterByPage(VoteRegister voteRegister, Long pageNum, Long pageSize) {
        PageMessage<VoteRegisterDto> msg = new PageMessage<>();
        msg.setCode(0);
        if(voteRegister.getActiveId()!=null) {
            Page<VoteRegisterDto> data = voteRegisterService.selectRegisterByPage(voteRegister, pageNum, pageSize);
            if (data != null && data.getSize() > 0) {
                msg.setCode(1);
                msg.setPagedata(data);
            } else {
                msg.setMsg("没有查询到相应数据");
            }
        }else {
            msg.setMsg("活动状态异常");
        }
        return msg;
    }

    @ApiOperation("删除参与活动选手")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "主键 当前选手报名id 必传"),
            @ApiImplicitParam(name = "activeId", value = "当前活动id 必传"),
            @ApiImplicitParam(name = "currentUserId", value = "当前操作人id 必传"),
    })
    @PostMapping("/delete")
    @Transactional(rollbackFor = {RuntimeException.class, Error.class}, isolation = Isolation.DEFAULT)
    public BaseMessage deleteRegister(Integer currentUserId, VoteRegister voteRegister) {
        BaseMessage msg = new BaseMessage();
        msg.setCode(0);
        Integer activeId = voteRegister.getActiveId();
        Integer registerId = voteRegister.getId();
        //活动是否存在
        if (isActiveExist(activeId)) {
            //操作人是否是主办方
            if (isCreateUser(activeId, currentUserId)) {
                //活动是否开始
                if (!isActiveStart(activeId)) {
                    //删除用户行为记录信息
                    int j = userBehaviorService.deleteRegister(registerId);
                    //删除参加选手记录
                    int i = voteRegisterService.deleteRegister(registerId);
                    if (i > 0 && j>0) {
                        msg.setCode(1);
                        msg.setMsg("删除成功");
                    } else {
                        msg.setMsg("删除失败");
                    }
                } else {
                    msg.setMsg("活动已开始，删除选手失败");
                }
            } else {
                msg.setMsg("未拥有操作选手信息权限");
            }
        } else {
            msg.setMsg("活动不存在");
        }
        return msg;
    }

    @ApiOperation("审核参与活动选手")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "主键 当前选手报名id 必传"),
            @ApiImplicitParam(name = "activeId", value = "当前活动id 必传"),
            @ApiImplicitParam(name = "status", value = "审核结果 必传"),
            @ApiImplicitParam(name = "currentUserId", value = "当前操作人id 必传"),
    })
    @PostMapping("/audit")
    public BaseMessage auditRegister(Integer currentUserId, VoteRegister voteRegister){
        BaseMessage msg = new BaseMessage();
        msg.setCode(0);
        Integer status = voteRegister.getStatus();
        Integer registerId = voteRegister.getId();
        Integer activeId = voteRegister.getActiveId();
        VoteRegister nowVoteRegister = voteRegisterService.selectById(registerId);
        if (isActiveExist(activeId)) {
            if (isCreateUser(activeId, currentUserId)) {
                if (status == 1 || status == -1) {
                    if (nowVoteRegister != null && nowVoteRegister.getFormContent() != null && !"[]".equals(nowVoteRegister.getFormContent())) {
                        if (!voteRegister.getStatus().equals(nowVoteRegister.getStatus())) {
                            if (nowVoteRegister.getGroupId() != null) {
                                ActiveGroup group = activeGroupService.selectActiveGroupById(nowVoteRegister.getGroupId());
                                Integer different = group.getDifferent();
                                int num = voteRegisterService.countOneUserVoteInActive(nowVoteRegister.getActiveId(), nowVoteRegister.getUserId());
                                if (num > different) {
                                    msg.setMsg("选手报名达到上限");
                                    return msg;
                                }
                            }
                            int i = voteRegisterService.updateVoteRegister(voteRegister);
                            if (i > 0) {
                                msg.setCode(1);
                                msg.setMsg("审核成功");
                            } else {
                                msg.setMsg("审核失败");
                            }
                        } else {
                            msg.setMsg("审核结果未改变");
                        }
                    } else {
                        msg.setMsg("选手报名信息不存在");
                    }
                } else {
                    msg.setMsg("审核结果错误");
                }
            } else {
                msg.setMsg("未拥有操作选手信息权限");
            }
        } else {
            msg.setMsg("活动不存在");
        }
        return msg;
    }

    @ApiOperation("查看展示一位选手个人及作品信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "主键 当前选手报名id 必传"),
            @ApiImplicitParam(name = "activeId", value = "当前活动id 必传"),
            @ApiImplicitParam(name = "currentUserId", value = "当前操作人id 必传"),
    })
    @GetMapping("/vote")
    public PojoMessage<VoteRegisterDto> selectVoteRegister(Integer currentUserId, VoteRegister voteRegister){
        PojoMessage<VoteRegisterDto> msg = new PojoMessage<>();
        msg.setCode(0);
        Integer registerId = voteRegister.getId();
        Integer activeId = voteRegister.getActiveId();
        VoteRegister nowVoteRegister = voteRegisterService.selectById(registerId);
        if (isActiveExist(activeId)) {
            if (isCreateUser(activeId, currentUserId)) {
                if (nowVoteRegister != null && nowVoteRegister.getFormContent() != null && !"[]".equals(nowVoteRegister.getFormContent())) {
                    List<VoteRegisterDto> list = voteRegisterService.selectVoteRegister(voteRegister);
                    VoteRegisterDto data = list.get(0);
                    if (data == null) {
                        msg.setMsg("未找到对应信息");
                    } else {
                        msg.setCode(1);
                        msg.setData(data);
                    }
                } else {
                    msg.setMsg("选手报名信息不存在");
                }
            } else {
                msg.setMsg("未拥有操作选手信息权限");
            }
        } else {
            msg.setMsg("活动不存在");
        }
        return msg;
    }

    @ApiOperation("查看展示一位用户的问卷或表单信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "主键 当前选手报名id 必传"),
            @ApiImplicitParam(name = "activeId", value = "当前活动id 必传"),
            @ApiImplicitParam(name = "currentUserId", value = "当前操作人id 必传"),
    })
    @GetMapping("/surveyform")
    public PojoMessage<VoteRegisterDtos> selectSurveyFormRegister(Integer currentUserId, VoteRegister voteRegister){
        PojoMessage<VoteRegisterDtos> msg = new PojoMessage<>();
        msg.setCode(0);
        Integer registerId = voteRegister.getId();
        Integer activeId = voteRegister.getActiveId();
        VoteRegister nowVoteRegister = voteRegisterService.selectById(registerId);
        if(nowVoteRegister!=null && nowVoteRegister.getFormContent()!=null && !"[]".equals(nowVoteRegister.getFormContent())){
            if(isActiveExist(activeId)){
                if(isCreateUser(activeId, currentUserId)){
                    List<VoteRegisterDtos> list = voteRegisterService.selectSurveyFormRegister(voteRegister);
                    VoteRegisterDtos data = list.get(0);
                    if(data==null){
                        msg.setMsg("未找到对应信息");
                    }else {
                        msg.setData(data);
                        msg.setCode(1);
                    }
                }else {
                    msg.setMsg("未拥有操作选手信息权限");
                }
            }else {
                msg.setMsg("活动不存在");
            }
        }else {
            msg.setMsg("个人基本信息不存在");
        }
        return msg;
    }

    /**
     * 活动是否存在
     *
     * @return
     */
    public boolean isActiveExist(Integer id) {
        ActiveTheme activeTheme = activeThemeService.selectById(id);
        if (activeTheme != null && activeTheme.getDeleted() == 0) {
            return true;
        }
        return false;
    }

    /**
     * 操作人是否为主办方
     *
     * @return
     */
    public boolean isCreateUser(Integer id, Integer createdUserId) {
        ActiveTheme activeTheme = activeThemeService.selectById(id);
        if (activeTheme != null && activeTheme.getCreatedUserId().equals(createdUserId)) {
            return true;
        }
        return false;
    }

    /**
     * 活动是否发布
     *
     * @return
     */
    public boolean isActivePublish(Integer id) {
        ActiveTheme activeTheme = activeThemeService.selectById(id);
        if (activeTheme != null && activeTheme.getPublished() == 1) {
            return true;
        }
        return false;
    }

    /**
     * 活动是否开始
     *
     * @return
     */
    public boolean isActiveStart(Integer id) {
        long nowDate = System.currentTimeMillis();
        ActiveTimeLine activeTimeLine = activeTimeLineService.selectById(id);
        if (nowDate >= activeTimeLine.getActiveStartLine()) {
            return true;
        }
        return false;
    }
}
